import axios from 'axios'

const api = axios.create({
  baseURL: '/api'
})

export const fetchPromptTemplates = async (category, tag) => {
  let url = '/prompt-templates'
  const params = {}
  
  if (category) {
    params.category = category
  }
  
  if (tag) {
    params.tag = tag
  }
  
  const response = await api.get(url, { params })
  return response.data
}

export const fetchPromptTemplate = async (id) => {
  const response = await api.get(`/prompt-templates/${id}`)
  return response.data
}

export const createPromptTemplate = async (data) => {
  const response = await api.post('/prompt-templates', data)
  return response.data
}

export const updatePromptTemplate = async (id, data) => {
  const response = await api.put(`/prompt-templates/${id}`, data)
  return response.data
}

export const deletePromptTemplate = async (id) => {
  const response = await api.delete(`/prompt-templates/${id}`)
  return response.data
}

export const processPromptTemplate = async (templateId, variables) => {
  try {
    console.log('Processing template with ID:', templateId);
    console.log('Variables type:', typeof variables);
    console.log('Variables content:', JSON.stringify(variables, null, 2));
    
    // 修改请求格式，匹配后端期望的 PromptTemplateUse 格式
    const requestData = {
      variable_values: variables
    };
    console.log('Request data:', JSON.stringify(requestData, null, 2));
    
    const response = await api.post(`/prompt-templates/${templateId}/process`, requestData);
    console.log('Response received:', response.data);
    return response.data;
  } catch (error) {
    console.error('Error processing template:');
    console.error('Status:', error.response?.status);
    console.error('Status text:', error.response?.statusText);
    console.error('Error data:', error.response?.data);
    console.error('Error message:', error.message);
    console.error('Request config:', error.config);
    throw error;
  }
}

export const testPromptTemplate = async (templateId, modelId, variables) => {
  const response = await api.post(`/prompt-templates/${templateId}/test`, {
    model_id: modelId,
    variables
  })
  return response.data
} 